package aiowang.springframe.h2.dao.impl;

import aiowang.springframe.h2.dao.UserDao;
import aiowang.springframe.h2.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author aiowang
 * @description:
 * @date 2021/8/16 13:55
 */

@Repository
public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public List<User> listUser() {
        List<User> users = this.jdbcTemplate.query(
                "SELECT ID, user_name, age FROM USER",
                new RowMapper<User>() {
                    @Override
                    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                        User user = new User();
                        user.setId(rs.getInt("id"));
                        user.setUsername(rs.getString("user_name"));
                        user.setAge(rs.getInt("age"));
                        return user;
                    }
                });

        return users;
    }
}
